package com.heima.article.service.impl;

import com.heima.article.service.ApCollectionService;
import com.heima.article.thread.AppThreadLocalUtil;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApCollectionServiceImpl implements ApCollectionService {

    @Autowired
    private CacheService cacheService;
    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        //0.参数判空
        if (dto==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //1.获取参数
        Long entryId = dto.getEntryId();//文章id
        Short operation = dto.getOperation();//0收藏,1取消收藏

        ApUser user = AppThreadLocalUtil.getUser();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"用户不存在");
        }
        Integer userId = user.getId();
        //2.判断类型
        if(operation==0){
            //2.1收藏
            //2.2查重
            Object o = cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + entryId, userId.toString());
            if(o!=null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"已收藏");
            }
            //2.3插入记录
            Long timeMillis = System.currentTimeMillis();
            cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR+entryId,userId.toString(),timeMillis.toString());
        }else if(operation==1){
            //3取消收藏
            cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR+entryId,userId.toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
